$.lp = {
    userId:"",
    registerU:false,
    init: function(){
        
        $(window).load(function(){
             //Sport Menu Layout fix
            var menuSize = $(window).width();
            var width = 0;  
            $(".sportsMenu ul").children("li").each(function(){
                width +=$(this).outerWidth();

            });

            var margin = (menuSize - width)/17;
            $(".sportsMenu ul").children("li").not(":first-child").css({"margin-left":+margin+"px"});
        });
        $(document).ready(function(){
            resizeLayout();
            
            
            //profile hover
            $(".login-btn").hover(function(){
                $(this).find(".profilePicWrapper").css({"height":"auto"});
                $(this).find("#dropdown-menu").css({"height":"auto"});
            },function(){
                $(this).find(".profilePicWrapper").css({"height":"100%"});
                $(this).find("#dropdown-menu").css({"height":"0px"});
            });
            
            
            $("header").hover(function(){
                $("header").removeClass("collided");
                $(".sportsMenu").height(46);
                $(".select-menu").height(50);
                $("#upload li").css({"color":"#C1C1C1"});
                
            },function(){
                $("header").addClass("collided");
                $(".sportsMenu").height(0);
                $(".select-menu").height(0);
                $("#upload li").css({"color":"#fff"});
                $(".nav-menu").hide();
            });
            
            $(".connect").find("li").find("img").hover(function(){
                $(this).attr("src",$(this).attr("src").replace("ico","ico_h"));
            },function(){
                $(this).attr("src",$(this).attr("src").replace("ico_h","ico"));
            });
            $("#addBlog").on('click',function(){
                $("body").css({"overflow":"hidden"});
                $('#redactor').redactor({
                    focus: true,
                    autoresize: false
                }).empty();
                $("#blogBox").show().css({
                    "opacity":"1"
                });
                return false;
            });
            $(".sportsMenu").find("li").find("a").on('click',function(){
               $(this).toggleClass("ns");
            });
            $(".sportsMenu").find("li").find(".toggle").on('click',function(){
                if($(this).hasClass("deselect"))
                    $(".sportsMenu").find("li").find("a").removeClass("ns");
                else
                    $(".sportsMenu").find("li").find("a").addClass("ns");
               $(this).toggleClass("deselect");
            });
            $("#submitBlog").on('click',function(){
                var html = $('#redactor').getCode();
                var title = $("#blogBox").find("#blogtitle").val();
                var sdesc = $("#blogBox").find("#shortdesc").val();
                var thumb = $("#blogBox").find(".preview").find("#articlethumb").val();
                $.post("/blog/xhrBlog",{
                    html : html,
                    title:title,
                    sdesc:sdesc,
                    thumb:thumb,
                    user_id:$.lp.userId
                },function(response){
                    if(response){
                        $(".blogBox").empty().css({"width":"20%","height":"250px"}).html("<div class='blogDialog'><h4>Article Posted Succesfully</h4><p><span>Notice: </span> we want to keep leap as clean as possible to offer you better navigation and fast information with good quality, this is why our team will check your article for legacy and quality and come back to you ! Thank you For </p></div>").find(".blogDialog").css({"opacity":"1"});
                    }
                });
                return false;
            })
            
            $('#shotView,#blogBox').on('click', function(e) {
                e.stopPropagation();
            });

            $("body").on('click','.register', function(e) {
                e.stopPropagation();
                return false;
            });
            $('html').on('click',function(e) {
                $("#registerUser").remove();
                $("body").css({"overflow":"auto"});
                $(".mainBlock").css({
                    "overflow":"hidden"
                });
                $(".mainBlock").find("img").css({"z-index":"1"});
                $(".mainBlock").find(".stopScale").removeClass("stopScale").addClass("scalable");
                $(".profileInfo").hide();
                $("#not-lstWrapper").hide();
                $(".search-result").hide();
                if(!$("#login").is(":hover")){
                    $(".overlay_bg").hide();
                }
                $(".nav-menu").hide();
                $("#shotView").hide().empty().html('<div id="shotContaier"><a id="shotUser" href="#"><span id="videoTitle"></span></a><a target="_blank" href="#" id="imageBox"><span class="imageholder"><img src="" id="imageContainer"></span><i></i></a><div id="infoBox"><span id="shotLikes" class="infoBlock" ><span>likes</span></span><span id="shotComments" class="infoBlock"><span>Time</span></span><span id="shotViews" class="infoBlock"><span>views</span></span></div><div id="commentBlock"><div class="comment" style="display: block;"></div></div></div>');
                $("#articleView").hide().empty().html('<div id="shotContaier"><a id="shotUser" href="#"><span id="videoTitle"></span></a><a target="_blank" href="#" id="imageBox"><span class="imageholder"><img src="" id="imageContainer"></span><i></i></a><div id="infoBox"><span id="shotLikes" class="infoBlock" ><span>likes</span></span><span id="shotComments" class="infoBlock"><span>Time</span></span><span id="shotViews" class="infoBlock"><span>views</span></span></div><div id="commentBlock"><div class="comment" style="display: block;"></div></div></div>');
                $(".redactor_dropdown").remove();
            });
    
            $(document).keyup(function(e) {
                if (e.keyCode == 27) {
                   
                    $("#registerUser").remove();
                    $(".redactor_dropdown").remove();
                    $("body").css({"overflow":"auto"});
                    $(".mainBlock").css({
                        "overflow":"hidden"
                    });
                    $(".mainBlock").find(".stopScale").removeClass("stopScale").addClass("scalable");
                    $(".profileInfo").hide();
                    $("#not-lstWrapper").hide();
                    $(".search-result").hide();
                    if(!$("#login").is(":hover")){
                        $(".overlay_bg").hide();
                    }
                    $(".nav-menu").hide();
                    $("#blogBox").hide().html('<div class="blogBox"><div class="addBlogHeader"><h4 style="">Add a Blog Entry:</h4></div><div class="blogTitle"><label>Title</label><input type="text" id="blogtitle" maxlength="40"/></div><div class="shortDesc" ><label>Short Description</label><input type="text" id="shortdesc" maxlength="300" /></div><div class="overlay_content_main"><div class="progress"><div class="bar"></div></div><div class="preview"><input type="hidden" id="articlethumb" name="articlethumb"/></div><form id="profilePicform" method="post" enctype="multipart/form-data" action="/profile/upload_picture"><div class="photoimg_upload"><span class="button">Upload Picture</span><input type="file" name="photoProfile" id="photoProfile" class="uploadPic"/>\n\
                </div>\n\
            </form>\n\
        </div>\n\
        <textarea id="redactor"></textarea>\n\
        <div class="submitBlog">\n\
            <button id="submitBlog" class="button">Publish</button>\n\
        </div>\n\
        </div>');
                    $("#shotView").hide().empty().html('<div id="shotContaier"><a id="shotUser" href="#"><span id="videoTitle"></span></a><a target="_blank" href="#" id="imageBox"><span class="imageholder"><img src="" id="imageContainer"></span><i></i></a><div id="infoBox"><span id="shotLikes" class="infoBlock" ><span>likes</span></span><span id="shotComments" class="infoBlock"><span>Time</span></span><span id="shotViews" class="infoBlock"><span>views</span></span></div><div id="commentBlock"><div class="comment" style="display: block;"></div></div></div>');
                    $("#articleView").hide().empty().html('<div id="shotContaier"><a id="shotUser" href="#"><span id="videoTitle"></span></a><a target="_blank" href="#" id="imageBox"><span class="imageholder"><img src="" id="imageContainer"></span><i></i></a><div id="infoBox"><span id="shotLikes" class="infoBlock" ><span>likes</span></span><span id="shotComments" class="infoBlock"><span>Time</span></span><span id="shotViews" class="infoBlock"><span>views</span></span></div><div id="commentBlock"><div class="comment" style="display: block;"></div></div></div>');
                }   // esc
                return false;
            });
            
            
            $('.changeCover').on('click',function(){
                $('#overlay_uploadC').show();
                $('.overlay_bg').show();
                return false;
            });
    
    
            $(".changeProfilePicture").on('click',function(){
                $('#overlay_uploadPP').show();
                $('.overlay_bg').show();
                return false;
            });
    
            var focus;
            $("input,textarea").focus(function(){
                focus = $(this).attr("placeholder")
                $(this).attr("placeholder", "");
            });
    
            $("input,textarea").focusout(function(){
                $(this).attr("placeholder", focus);
            });
    
            $("#notifications").on('click',function(){
                $.getJSON('/notification/getNotifications' ,function(data){
                    var output="";
                    $("#notifications").find("#not-lstWrapper").show();
                    $.each(data,function(key,value){
                        var status;
                        if(key != 0)
                            output += '<li class="dropdown-divider"></li>';
                        if(value.status === "new")
                            status = "class='new'";
                        var list = "<li "+status+">\n\
                                <img class='profile' src="+value.user_from_thumb+" width='30px' height='30px' />\n\
                                <div><a>"+value.user_name_from+"</a> "+value.action+" your "+value.identifier+"</div>\
                                <img width='50px' height='30px' src="+value.thumb+" />\n\
                                </li>";
                        output += list;
                    });
                    if(data.length == 0){
                        $("#notifications").find("#not-lstWrapper").addClass('emtpy-list');
                        output = "<li>This list is empty</li>";
                    }
                    $("#notifications").find("#not-lst").empty().append(output).show();
                    $("#notifications").find('i').remove();
                });
            });
    
            $('.selectbox').on('click',function(){
                $(".nav-menu").hide();
                var left = $(this).offset().left-1;
                $(this).next().children("ul").css({"left":left+"px"}).show();
                return false;
            });
    
            $('.searchbox_submit').on('click',function(){
                if($(".searchbox").val() !== ""){
                    $.getJSON('/home/search?name='+$(".searchbox").val(),function(data){
                        var list = "";
                        $.each(data,function(key,value){
                            var comma="";
                            if(value.country !== "")
                                comma=",";
                    
                            list += "<li><img src='"+value.profile_pic_thumb+"' />\n\
                        <p class='name_info'>"+value.first_name+" "+value.last_name+"</p>\n\
                        <p class='location_info'>"+value.city+comma+" "+value.country+"</p></li>";
                        });
                        $(".search-result").empty().append(list).show();
                    });
                }
                return false;
            });
            
            $(".searchbox").focus(function() {
                
                if($("body").hasClass("small")){
                    $("#searchwrapper").css({"position":"absolute","width":"700px"});
                }else if($("body").hasClass("middle")){
                    $("#searchwrapper").css({"position":"absolute","width":"750px"});
                }else{
                    $("#searchwrapper").css({"position":"absolute","width":"900px"});
                }
            });
            
            $(".searchbox").focusout(function() {
                if($("body").hasClass("small")){
                    $("#searchwrapper").css({"position":"relative","width":"198px"});
                }else if($("body").hasClass("middle")){
                    $("#searchwrapper").css({"position":"relative","width":"248px"});
                }else{
                    $("#searchwrapper").css({"position":"relative","width":"298px"});
                }
                
            });
            
            $(window).resize(function() {
                resizeLayout();

            });
    
            $(".login-social").on('click',function(){
                return false; 
            });
    
            $(".mainBlock").on('click',function(){
                
                $(this).find("img").css({"z-index":"9994"}).removeClass("scalable").addClass("stopScale");
                $(this).css({
                    "overflow":"visible"
                });
                $(".profileInfo").hide();
                $('.overlay_bg').show();
                
                var elementScroll = $(this).offset().top - $(this).parent().offset().top;
                var eTop = $(window).height()/2 - $(this).parent().offset().top -100;
                var eLeft = $(this).offset().left;
                var eRight = $(window).width() - $(this).offset().left;
                var eBottom = elementScroll - $(window).scrollTop();

                    if($("body").hasClass("small")){
                        $(this).find(".profileInfo").show().css({
                            "top":"200px",
                            "opacity":"1"
                        });
                        $(this).find(".triangle").css({
                            "top":"-29px"
                        });                
                    }else if($("body").hasClass("middle")){
                        $(this).find(".profileInfo").show().css({
                            "top":"250px",
                            "opacity":"1"
                        }); 
                        $(this).find(".triangle").css({
                            "top":"-29px"
                        });
                    }else{
                        $(this).find(".profileInfo").show().css({
                            "top":"300px",
                            "opacity":"1"
                        }); 
                        $(this).find(".triangle").css({
                            "top":"-29px"
                        });
                    }
                return false;
            });
    
            //video Click
    
            $(document).find('.videoPost').on('click',function(event){
                $("body").css({"overflow":"hidden"});
                $("#shotView").show().css({
                    "opacity":"1"
                });
                var id = $(this).attr('id');
                var title, comments_count, likes, duration, views;
            
                $("#shotView").find("#shotContaier").addClass(id);
                $.get("https://gdata.youtube.com/feeds/api/videos/"+id+"?v=2&alt=json",function(video){
                
                    title = video.entry.title.$t;
                    comments_count = video.entry.gd$comments.gd$feedLink.countHint;
                    likes = video.entry.yt$rating.numLikes;
            
                    duration = video.entry.media$group.yt$duration.seconds;
                    var mod = duration % 60;
                    if (mod< 10)
                        mod = "0"+mod;
                    duration = Math.floor(duration/60) +":"+ mod;
                    views = video.entry.yt$statistics.viewCount;
            
                    var videoEmbed;
                    if($(this).parents(".videos").hasClass("xvideos")){
                        videoEmbed = '<iframe class="youtube-player" type="text/html" width="638" height="505"  src="http://flashservice.xvideos.com/embedframe/'+id+'" frameborder="0" allowfullscreen ></iframe>';
                    }
                    else{
                        videoEmbed = '<iframe id="ytplayer" type="text/html" width="638" height="505" src="http://www.youtube.com/embed/'+id+'?autoplay=1" frameborder="0"/>';
                    }
            
                    $($("#imageBox")).empty().html(videoEmbed);
                    $("#shotView").find("#shotUser").find("#videoTitle").text(title);
                    $("#shotView").find(".comment").text(comments_count);
            
                    $("#shotContaier").animate({
                        transform: 'scale(1,1)'
                    });
                    $("#shotView").find("#shotLikes").html(likes+"<span>likes</span>");
                    $("#shotView").find("#shotComments").html(duration+"<span>duration</span>");
                    $("#shotView").find("#shotViews").html(views+"<span>views</span>");
                    $("#shotView").find("#shotContaier").addClass("noTrans");
                });
            
                return false;
            });
            $(document).find('.article').on('click',function(event){
                $("body").css({"overflow":"hidden"});
                $("#articleView").show().css({
                    "opacity":"1"
                });
                var title, comments_count, likes, duration, views, body, user;
                            
                title = $(this).find(".mediaInfos").find("strong").text();
                body = $(this).find(".mediaInfos").find(".articleBody").html();
                user = $(this).find(".mediaInfos").find(".videoUser").clone();
                comments_count = 0;
                likes = 0;

                duration = 0;
                
                views = 0;


                $("#articleView").find("#imageBox").empty().html(body);
                $("#articleView").find("#shotUser").find("#videoTitle").text(title);
                $("#articleView").find("#shotUser").prepend(user);
                $("#articleView").find(".comment").text(comments_count);

                $("#shotContaier").animate({
                    transform: 'scale(1,1)'
                });
                $("#articleView").find("#shotLikes").html(likes+"<span>likes</span>");
                $("#articleView").find("#shotComments").html(duration+"<span>duration</span>");
                $("#articleView").find("#shotViews").html(views+"<span>views</span>");
                $("#articleView").find("#shotContaier").addClass("noTrans");
            
                return false;
            });
            // Upload Article Picture
            $('.uploadPic').on('change',function(){ 
            var bar = $('.bar');
            var status = $('.preview').find("#articlethumb");
            $(this).parents("form").ajaxForm({
//                target: '.preview',
                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                },
                complete: function(xhr) {
                    status.val(xhr.responseText);
                    bar.css({"background-color":"#B42515"});
                }
            }).submit();
		
        });
        });
    },
    register: function(){
         $("body").on("click",".submit", function(){
           var firstname = $(".register").find(".editName").text().split(/ (.+)?/)[0]; 
           var lastname = $(".register ").find(".editName").text().split(/ (.+)?/)[1]; 
           var location = $(".register ").find(".editLocation").text();
           
           var username = $("tr#usernameH").find("td.editUsername").text(); 
           var email = $("tr#emailH").find("td.editEmail").text(); 
           var pass = $("tr#passH").find("td.editPass").find("input").val(); 
           var pass2 = $("tr#pass2H").find("td.editPass2").find("input").val(); 
           var image = $("#drop").attr("src"); 
           var imagename = $("#drop").attr("title");
           
           $("#first_name").val(firstname);
           $("#last_name").val(lastname);
           $("#country").val(location);
           $("#email_address").val(email);
           $("#username").val(username);
           $("#password").val(pass);
           $("#password2").val(pass2);
           $("#image").val(image);
           $("#imagename").val(imagename)
           $("#registration").submit();
           return false;
        });
        
        

        $("body").on("click",".editName", function(){
           if($(this).text() === "ADD YOUR NAME")
                $(this).text(""); 
        });
        $("body").on("focus",".editName", function(){
           if($(this).text() === "ADD YOUR NAME")
                $(this).text(""); 
        });
        $("body").on("focusout",".editName", function(){
           if($(this).text() === ""){
               $(this).text("ADD YOUR NAME");
           }
        });
        
        $("body").on("click",".editLocation", function(){
           if($(this).text() === "ADD YOUR LOCATION")
                $(this).text(""); 
        });
        $("body").on("focus",".editLocation", function(){
          if($(this).text() === "ADD YOUR LOCATION")
                $(this).text(""); 
        });
        $("body").on("focusout",".editLocation", function(){
           if($(this).text() === ""){
               $(this).text("ADD YOUR LOCATION");
           }
        });
        $("a.registered-users").click(function() {
            if($("#registerUser").length > 0)
                return false
            $(".slider").animate({"height":"0"},500);
            //$("html, body").animate({scrollTop: sliderH}, "slow");
            $.lp.registerU = true;
            
            var top = 0;
            if($("body").hasClass("big"))
                top = 300;
            else if($("body").hasClass("big"))
                top = 250;
            else
                top = 200;
            
            var html = '<a href="#" id="registerUser" class="mainBlock register" style="overflow: visible;background:#fff;z-index:999;" ondragenter="return false" ondragover="return false" ondrop="dropIt(event)"><img id="drop" src="/public/images/empty.png" alt="" class="desaturate" width="150" height="150" style="z-index: 1;" /><span class="dragnbrowse" id="dropInfos">Drag and drop an image here or <span class="trig">browse </span>  your computer</span>\n\
                <div class="profileInfo" style="display: block;  opacity: 1;">\n\
                    <div class="triangle arrow-up" style="top: -29px;"></div>\n\
                    <div class="personalInfos"><h4 class="editName" contentEditable="true">ADD YOUR NAME</h4></div><div class="moreInfos" style="height:auto;"><h4 class="editLocation" contentEditable="true">ADD YOUR LOCATION</h4></div>\n\
            <div class="registerInfos">\n\
            <table>\n\
            <tbody>\n\
                 <tr id="usernameH"><td style="width:25%;background:#fff;" colspan="1">Username:</td><td class="editUsername" style="width:73%;" colspan="3" contentEditable="true"></td></tr>\n\
                 <tr id="emailH"><td style="width:25%;background:#fff;" colspan="1">E-mail:</td><td class="editEmail" style="width:73%;" colspan="3" contentEditable="true"></td></tr>\n\
                 <tr id="passH"><td style="width:25%;background:#fff;" colspan="1">Pass:</td><td class="editPass" style="width:73%;" colspan="3" ><input type="password"  contentEditable="true" /></td></tr>\n\
                 <tr id="pass2H"><td style="width:25%;background:#fff;" colspan="1">Repeat Pass:</td><td class="editPass2" style="width:73%;" colspan="3"><input type="password"  contentEditable="true" /></td></tr>\n\
                 <tr id="usernameH"><td style="width:50%;background:#E43851;text-align:center;padding:0;" colspan="2"><a class="submit" href="#submit">SUBMIT</a></td><td style="width:50%;text-align:center;padding:0;" colspan="2"><a href="cancel">NO NO NO!</a></td></tr>\n\
            </tbody>             \n\
            </table>\n\
                <form id="registration" action="http://leapdemo.com/login/create_member" method="post" accept-charset="utf-8">\n\
                    <input type="hidden" placeholder="Firstname" name="first_name" id="first_name" value="" size="50"/>\n\
                    <input type="hidden" placeholder="Lastname" name="last_name" id="last_name" value="" size="50"/>\n\
                    <input type="hidden" placeholder="Country" name="country" id="country" value="" size="50"/>\n\
                    <input type="hidden" placeholder="Email" name="email_address" id="email_address" value="" size="50"/>\n\
                    <input type="hidden" placeholder="Username" name="username" id="username" value="" size="50"/>\n\
                    <input type="hidden" placeholder="Password" name="password" id="password" size="50" value=""/>\n\
                    <input type="hidden" placeholder="Confirm Password" name="password2" id="password2" size="50" value="" />\n\
                   <input type="hidden" placeholder="image name" name="imagename" id="imagename" value="" size="50"/>\n\
                     <input type="hidden" placeholder="image" name="image" id="image" value="" size="50"/>\n\
 </form>\n\
            </div>\n\
            </div></a>';
            $(".homeWrapper").prepend(html);
            $("body").prepend('<input type="file"  class="browseImage" name="browsefile" id="browsefile"/>');
            return false;
        });
        $("body").on('click','.trig', function() {
            $('#browsefile').trigger('click');
            return false;
        });
        $('body').on('click','#browsefile', function(e) {
                e.stopPropagation();
            });
        $('body').on("change", "#browsefile", function(){
            var file = document.getElementById('browsefile').files[0];
            if (file) {
                // create reader
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    // browser completed reading file - display it
                    document.getElementById('drop').src=e.target.result;
                    document.getElementById('drop').title=file.name;
                    var d = document.getElementById('registerUser');
                    var olddiv = document.getElementById('dropInfos');
                    d.removeChild(olddiv);
                };
            }
        });
    }
}
function resizeLayout(){
    
    
    
    var int;
    if(parseInt($(".sportsMenu").width()/150)>20 )
        int = 20;
    else
        int = $(".sportsMenu").width()/150;
    
    var width = $(window).width()/6;
    $(".sportsMenu").find("li").css({"font-size":int+"px"});
    $(".mainBlock").width(width);
    $(".mainBlock").height(width);
    $(".selectwrapper, .nav-menu").width(width-1.2);
    $("#leap").width(width-1);
    $("#searchwrapper").width(width);
    $(".searchbox").width(width*2-40);
    $("#upload,.connect,.login-btn").width(width);
    if($(window).width() < 1250){
        $("body").attr('class','small');
    }
    else if($(window).width() >= 1250 && $(window).width() < 1500){
        $("body").attr('class','middle');
    }
    else{
        $("body").attr('class','big');
    }
    
     
    //Sport Menu Layout fix
    var menuSize = $(window).width();
    var width = 0;  
    $(".sportsMenu ul").children("li").each(function(){
        width +=$(this).outerWidth();

    });

    var margin = (menuSize - width)/17;
    $(".sportsMenu ul").children("li").not(":first-child").css({"margin-left":+margin+"px"});
}
function imagesSelected(myFiles) {
  for (var i = 0, f; f = myFiles[i]; i++) {
    if (!myFiles[i].type.match('image.*')) {
        alert("only images")
    }
    var imageReader = new FileReader();
    imageReader.onload = (function(aFile) {
      return function(e) {
        var span = "";

        span.innerHTML = ['<img class="images" src="', e.target.result,'" title="', aFile.name, '"/>'].join('');
        document.getElementById('drop').src=e.target.result;
        document.getElementById('drop').title=aFile.name;
        var d = document.getElementById('registerUser');
        var olddiv = document.getElementById('dropInfos');
        d.removeChild(olddiv);
        
      };
    })(f);
    imageReader.readAsDataURL(f);
  }
}

function dropIt(e) { 
   imagesSelected(e.dataTransfer.files);
   e.stopPropagation(); 
   e.preventDefault();  
} 